#ifndef TCP_SERVER_ASYNCLOGGING_H
#define TCP_SERVER_ASYNCLOGGING_H

#include "../thread/Mutex.h"
#include "../thread/Thread.h"
#include "LogStream.h"
#include "../noncopyable.h"

#include <atomic>
#include <vector>
#include <memory>

class AsyncLogging : muduo::noncopyable {
public:

    AsyncLogging(const string &basename,
                 off_t rollSize,
                 int flushInterval = 3);

    ~AsyncLogging() {
        if (running_) {
            stop();
        }
    }

    void append(const char *logline, int len);

    /**
     * 启动异步线程
     */
    void start() {
        running_ = true;
        thread_.start();
        latch_.wait();
    }

    /**
     * 停止异步线程
     */
    void stop() {
        running_ = false;
        cond_.notify();
        thread_.join();
    }

private:

    /**
     * 异步线程任务
     */
    void threadFunc();

    typedef detail::FixedBuffer<detail::kLargeBuffer> Buffer;
    typedef std::vector<std::unique_ptr<Buffer> > BufferVector;
    typedef BufferVector::value_type BufferPtr;

    const int flushInterval_;
    std::atomic<bool> running_;
    const string basename_;
    // 基本文件名
    const off_t rollSize_;
    // 文件最大写入数据量大小
    Thread thread_;
    CountDownLatch latch_;
    MutexLock mutex_;
    Condition cond_;
    BufferPtr currentBuffer_;
    // 当前缓冲区指针
    BufferPtr nextBuffer_;
    // 接下来的缓冲区指针
    BufferVector buffers_;
    // 缓冲区数组, 用于管理缓冲区
};


#endif //TCP_SERVER_ASYNCLOGGING_H
